import React, { useState, useMemo } from 'react';
import { useNavigate } from 'react-router-dom';
import {
  Box,
  Card,
  CardContent,
  Typography,
  Button,
  IconButton,
  TextField,
  FormControl,
  InputLabel,
  Select,
  MenuItem,
  Grid,
  Chip,
  Menu,
  Avatar,
  Dialog,
  DialogTitle,
  DialogContent,
  DialogActions,
  Alert,
  Switch,
  FormControlLabel
} from '@mui/material';
import {
  Add as AddIcon,
  Search as SearchIcon,
  MoreVert as MoreVertIcon,
  Work as WorkIcon,
  Business as BusinessIcon,
  Edit as EditIcon,
  Delete as DeleteIcon,
  Security as SecurityIcon,
  Refresh as RefreshIcon
} from '@mui/icons-material';
import { useQuery, useMutation, useQueryClient } from '@tanstack/react-query';
import { useForm, Controller } from 'react-hook-form';
import { PageHeader } from '@/components/common/PageHeader';
import { positionService } from '@/services/positionService';
import { departmentService } from '@/services/departmentService';
import type { Position, Department, CreatePositionRequest } from '@/types';

interface CreatePositionFormData {
  name: string;
  code: string;
  description?: string;
  departmentId: string;
  level: number;
  status: 'active' | 'inactive';
}

const PositionListPage: React.FC = () => {
  const navigate = useNavigate();
  const queryClient = useQueryClient();
  const [searchTerm, setSearchTerm] = useState('');
  const [selectedDepartment, setSelectedDepartment] = useState<string>('all');
  const [selectedStatus, setSelectedStatus] = useState<string>('all');
  const [anchorEl, setAnchorEl] = useState<null | HTMLElement>(null);
  const [selectedPosition, setSelectedPosition] = useState<Position | null>(null);
  const [createDialogOpen, setCreateDialogOpen] = useState(false);
  const [deleteDialogOpen, setDeleteDialogOpen] = useState(false);
  const [groupByDepartment, setGroupByDepartment] = useState(true);

  const {
    control,
    handleSubmit,
    reset,
    setValue,
    watch,
    formState: { errors, isValid }
  } = useForm<CreatePositionFormData>({
    defaultValues: {
      name: '',
      code: '',
      description: '',
      departmentId: '',
      level: 1,
      status: 'active'
    },
    mode: 'onChange'
  });

  // 获取岗位列表
  const { data: positions = [], isLoading: positionsLoading } = useQuery({
    queryKey: ['positions'],
    queryFn: () => positionService.getPositions({})
  });

  // 获取部门列表
  const { data: departments = [], isLoading: departmentsLoading } = useQuery({
    queryKey: ['departments'],
    queryFn: () => departmentService.getDepartments({})
  });

  // 创建岗位
  const createPositionMutation = useMutation({
    mutationFn: (data: CreatePositionRequest) => positionService.createPosition(data),
    onSuccess: () => {
      queryClient.invalidateQueries({ queryKey: ['positions'] });
      setCreateDialogOpen(false);
      reset();
    }
  });

  // 删除岗位
  const deletePositionMutation = useMutation({
    mutationFn: (id: string) => positionService.deletePosition(id),
    onSuccess: () => {
      queryClient.invalidateQueries({ queryKey: ['positions'] });
      setDeleteDialogOpen(false);
      setSelectedPosition(null);
    }
  });

  // 过滤岗位
  const filteredPositions = useMemo(() => {
    return positions.filter((position: Position) => {
      const matchesSearch = !searchTerm ||
        position.name.toLowerCase().includes(searchTerm.toLowerCase()) ||
        position.code.toLowerCase().includes(searchTerm.toLowerCase());
      
      const matchesDepartment = selectedDepartment === 'all' || position.departmentId === selectedDepartment;
      const matchesStatus = selectedStatus === 'all' || position.status === selectedStatus;
      
      return matchesSearch && matchesDepartment && matchesStatus;
    });
  }, [positions, searchTerm, selectedDepartment, selectedStatus]);

  // 岗位级别映射
  const getLevelText = (level: number) => {
    const levelMap: Record<number, string> = {
      1: '初级',
      2: '中级', 
      3: '高级',
      4: '资深',
      5: '专家'
    };
    return levelMap[level] || `第${level}级`;
  };

  const handleCreatePosition = (data: CreatePositionFormData) => {
    createPositionMutation.mutate(data);
  };

  const handleDeletePosition = () => {
    if (selectedPosition) {
      deletePositionMutation.mutate(selectedPosition.id);
    }
  };

  const handleMenuClose = () => {
    setAnchorEl(null);
    setSelectedPosition(null);
  };

  // 根据名称自动生成岗位代码
  const positionName = watch('name');
  React.useEffect(() => {
    if (positionName) {
      const code = positionName
        .toLowerCase()
        .replace(/[\s\u4e00-\u9fa5]/g, '_')
        .replace(/[^a-z0-9_]/g, '')
        .replace(/_+/g, '_')
        .replace(/^_|_$/g, '');
      setValue('code', code.toUpperCase());
    }
  }, [positionName, setValue]);

  return (
    <Box sx={{ p: 3 }}>
      <PageHeader
        title="岗位管理"
        description="管理组织岗位信息和数据权限"
        action={
          <Box sx={{ display: 'flex', gap: 1 }}>
            <FormControlLabel
              control={
                <Switch
                  checked={groupByDepartment}
                  onChange={(e) => setGroupByDepartment(e.target.checked)}
                  size="small"
                />
              }
              label="按部门分组"
            />
            <Button
              variant="contained"
              startIcon={<AddIcon />}
              onClick={() => setCreateDialogOpen(true)}
            >
              创建岗位
            </Button>
          </Box>
        }
      />

      {/* 搜索和筛选 */}
      <Card sx={{ mb: 3 }}>
        <CardContent>
          <Grid container spacing={2} alignItems="center">
            <Grid item xs={12} md={4}>
              <TextField
                fullWidth
                placeholder="搜索岗位名称、代码..."
                value={searchTerm}
                onChange={(e) => setSearchTerm(e.target.value)}
                InputProps={{
                  startAdornment: <SearchIcon sx={{ color: 'text.secondary', mr: 1 }} />
                }}
              />
            </Grid>
            <Grid item xs={12} md={3}>
              <FormControl fullWidth>
                <InputLabel>部门</InputLabel>
                <Select
                  value={selectedDepartment}
                  label="部门"
                  onChange={(e) => setSelectedDepartment(e.target.value as string)}
                >
                  <MenuItem value="all">全部部门</MenuItem>
                  {departments.map((dept: Department) => (
                    <MenuItem key={dept.id} value={dept.id}>{dept.name}</MenuItem>
                  ))}
                </Select>
              </FormControl>
            </Grid>
            <Grid item xs={12} md={3}>
              <FormControl fullWidth>
                <InputLabel>状态</InputLabel>
                <Select
                  value={selectedStatus}
                  label="状态"
                  onChange={(e) => setSelectedStatus(e.target.value as string)}
                >
                  <MenuItem value="all">全部状态</MenuItem>
                  <MenuItem value="active">正常</MenuItem>
                  <MenuItem value="inactive">停用</MenuItem>
                </Select>
              </FormControl>
            </Grid>
            <Grid item xs={12} md={2}>
              <Typography variant="body2" color="text.secondary" align="right">
                共 {filteredPositions.length} 个岗位
              </Typography>
            </Grid>
          </Grid>
        </CardContent>
      </Card>

      {/* 岗位列表 */}
      {positionsLoading || departmentsLoading ? (
        <Card>
          <CardContent>
            <Typography>加载中...</Typography>
          </CardContent>
        </Card>
      ) : (
        <Card>
          <CardContent>
            {filteredPositions.length > 0 ? (
              <Grid container spacing={2}>
                {filteredPositions.map((position: Position) => {
                  const department = departments.find((d: Department) => d.id === position.departmentId);
                  return (
                    <Grid item xs={12} sm={6} md={4} key={position.id}>
                      <Card
                        sx={{
                          cursor: 'pointer',
                          '&:hover': { boxShadow: 4 }
                        }}
                      >
                        <CardContent>
                          <Box sx={{ display: 'flex', justifyContent: 'space-between', alignItems: 'flex-start', mb: 2 }}>
                            <Avatar sx={{ bgcolor: 'secondary.main' }}>
                              <WorkIcon />
                            </Avatar>
                            <IconButton
                              size="small"
                              onClick={(e) => {
                                e.stopPropagation();
                                setSelectedPosition(position);
                                setAnchorEl(e.currentTarget);
                              }}
                            >
                              <MoreVertIcon />
                            </IconButton>
                          </Box>
                          
                          <Typography variant="h6" sx={{ mb: 1 }}>
                            {position.name}
                          </Typography>
                          
                          <Typography variant="body2" color="text.secondary" sx={{ mb: 2 }}>
                            {position.description || '暂无描述'}
                          </Typography>
                          
                          <Box sx={{ display: 'flex', flexDirection: 'column', gap: 1 }}>
                            <Box sx={{ display: 'flex', justifyContent: 'space-between' }}>
                              <Typography variant="caption" color="text.secondary">
                                所属部门
                              </Typography>
                              <Typography variant="caption">
                                {department?.name || '未分配'}
                              </Typography>
                            </Box>
                            
                            <Box sx={{ display: 'flex', justifyContent: 'space-between' }}>
                              <Typography variant="caption" color="text.secondary">
                                岗位级别
                              </Typography>
                              <Chip
                                label={getLevelText(position.level)}
                                size="small"
                                color="primary"
                                variant="outlined"
                              />
                            </Box>
                            
                            <Box sx={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center' }}>
                              <Typography variant="caption" color="text.secondary">
                                状态
                              </Typography>
                              <Chip
                                label={position.status === 'active' ? '正常' : '停用'}
                                size="small"
                                color={position.status === 'active' ? 'success' : 'default'}
                                variant="outlined"
                              />
                            </Box>
                          </Box>
                        </CardContent>
                      </Card>
                    </Grid>
                  );
                })}
              </Grid>
            ) : (
              <Alert severity="info">暂无符合条件的岗位</Alert>
            )}
          </CardContent>
        </Card>
      )}

      {/* 岗位操作菜单 */}
      <Menu
        anchorEl={anchorEl}
        open={Boolean(anchorEl) && Boolean(selectedPosition)}
        onClose={handleMenuClose}
      >
        <MenuItem onClick={() => {
          navigate(`/positions/${selectedPosition?.id}/edit`);
          handleMenuClose();
        }}>
          <EditIcon sx={{ mr: 1 }} />
          编辑岗位
        </MenuItem>
        <MenuItem onClick={() => {
          navigate(`/positions/${selectedPosition?.id}/permissions`);
          handleMenuClose();
        }}>
          <Security sx={{ mr: 1 }} />
          数据权限
        </MenuItem>
        <MenuItem 
          onClick={() => {
            setDeleteDialogOpen(true);
            handleMenuClose();
          }}
          sx={{ color: 'error.main' }}
        >
          <DeleteIcon sx={{ mr: 1 }} />
          删除岗位
        </MenuItem>
      </Menu>

      {/* 创建岗位对话框 */}
      <Dialog
        open={createDialogOpen}
        onClose={() => {
          setCreateDialogOpen(false);
          reset();
        }}
        maxWidth="md"
        fullWidth
      >
        <DialogTitle>创建岗位</DialogTitle>
        <form onSubmit={handleSubmit(handleCreatePosition)}>
          <DialogContent>
            <Grid container spacing={2} sx={{ mt: 1 }}>
              <Grid item xs={12} sm={6}>
                <Controller
                  name="name"
                  control={control}
                  rules={{ required: '岗位名称不能为空' }}
                  render={({ field }) => (
                    <TextField
                      {...field}
                      label="岗位名称"
                      fullWidth
                      error={!!errors.name}
                      helperText={errors.name?.message}
                    />
                  )}
                />
              </Grid>
              <Grid item xs={12} sm={6}>
                <Controller
                  name="code"
                  control={control}
                  rules={{ required: '岗位代码不能为空' }}
                  render={({ field }) => (
                    <TextField
                      {...field}
                      label="岗位代码"
                      fullWidth
                      error={!!errors.code}
                      helperText={errors.code?.message}
                    />
                  )}
                />
              </Grid>
              <Grid item xs={12}>
                <Controller
                  name="description"
                  control={control}
                  render={({ field }) => (
                    <TextField
                      {...field}
                      label="岗位描述"
                      fullWidth
                      multiline
                      rows={3}
                    />
                  )}
                />
              </Grid>
              <Grid item xs={12} sm={4}>
                <Controller
                  name="departmentId"
                  control={control}
                  rules={{ required: '请选择所属部门' }}
                  render={({ field }) => (
                    <FormControl fullWidth error={!!errors.departmentId}>
                      <InputLabel>所属部门</InputLabel>
                      <Select {...field} label="所属部门">
                        {departments.map((dept: Department) => (
                          <MenuItem key={dept.id} value={dept.id}>
                            {dept.name}
                          </MenuItem>
                        ))}
                      </Select>
                    </FormControl>
                  )}
                />
              </Grid>
              <Grid item xs={12} sm={4}>
                <Controller
                  name="level"
                  control={control}
                  render={({ field }) => (
                    <FormControl fullWidth>
                      <InputLabel>岗位级别</InputLabel>
                      <Select {...field} label="岗位级别">
                        {[1, 2, 3, 4, 5].map(level => (
                          <MenuItem key={level} value={level}>{getLevelText(level)}</MenuItem>
                        ))}
                      </Select>
                    </FormControl>
                  )}
                />
              </Grid>
              <Grid item xs={12} sm={4}>
                <Controller
                  name="status"
                  control={control}
                  render={({ field }) => (
                    <FormControl fullWidth>
                      <InputLabel>状态</InputLabel>
                      <Select {...field} label="状态">
                        <MenuItem value="active">正常</MenuItem>
                        <MenuItem value="inactive">停用</MenuItem>
                      </Select>
                    </FormControl>
                  )}
                />
              </Grid>
            </Grid>
          </DialogContent>
          <DialogActions>
            <Button onClick={() => { setCreateDialogOpen(false); reset(); }}>
              取消
            </Button>
            <Button
              type="submit"
              variant="contained"
              disabled={!isValid || createPositionMutation.isPending}
            >
              {createPositionMutation.isPending ? '创建中...' : '创建'}
            </Button>
          </DialogActions>
        </form>
      </Dialog>

      {/* 删除确认对话框 */}
      <Dialog
        open={deleteDialogOpen}
        onClose={() => setDeleteDialogOpen(false)}
      >
        <DialogTitle>删除岗位</DialogTitle>
        <DialogContent>
          <Typography>
            确认删除岗位 "{selectedPosition?.name}"？
          </Typography>
          <Alert severity="warning" sx={{ mt: 2 }}>
            删除岗位将影响相关用户的岗位信息，请谨慎操作！
          </Alert>
        </DialogContent>
        <DialogActions>
          <Button onClick={() => setDeleteDialogOpen(false)}>
            取消
          </Button>
          <Button
            onClick={handleDeletePosition}
            color="error"
            variant="contained"
            disabled={deletePositionMutation.isPending}
          >
            {deletePositionMutation.isPending ? '删除中...' : '确认删除'}
          </Button>
        </DialogActions>
      </Dialog>
    </Box>
  );
};

// PositionListPage 已在上面定义
export const PositionCreatePage = () => (
  <Box sx={{ p: 3 }}>
    <PageHeader title="创建岗位" description="创建新的岗位" />
    <Typography>此页面正在开发中...</Typography>
  </Box>
);

export const PositionEditPage = () => (
  <Box sx={{ p: 3 }}>
    <PageHeader title="编辑岗位" description="编辑岗位信息" />
    <Typography>此页面正在开发中...</Typography>
  </Box>
);

export default PositionListPage;